﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.Entity.Core.Objects;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
namespace StorageManage.Logic
{
    public partial class StorageIn : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {
                method.Invoke(this, null);
            }
            catch
            {

                throw;
            }
        }
        public void GetStorageInList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(o=>o.Field=="StartTime").FirstOrDefault()!=null)
                {
                    listSearch.Where(o => o.Field == "StartTime").FirstOrDefault().Field = "ApplyTime";
                }
                if (listSearch.Where(o => o.Field == "EndTime").FirstOrDefault() != null)
                {
                    listSearch.Where(o => o.Field == "EndTime").FirstOrDefault().Field = "ApplyTime";
                }
            }
            string OrderId = OperateContext.Sort == null ? "ApplyTime" : OperateContext.Sort;
            Expression<Func<View_StorageIn, bool>> exp = SearchExpression.FindByGroup<View_StorageIn>(listSearch);
            var list = DALSession.Current.View_StorageInDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OperateContext.OrderDesc);
            int count = DALSession.Current.View_StorageInDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }
        public void GetTeam()
        {
            string q = Request.Form["q"];
            if (q == null)
            {
                Response.Write(JsonHelper.toJson(DALSession.Current.BD_DepInfoDAL.GetListBy(d => d.FatherId == 4 || d.FatherId == 19 || d.FatherId == 7).Select(o => new { value = o.ID, text = o.DepName })));
            }
            else
            {
                Response.Write(JsonHelper.toJson(DALSession.Current.BD_DepInfoDAL.GetListBy(d => (d.FatherId == 4 || d.FatherId == 19 || d.FatherId == 7) && d.DepName.Contains(Request.Form["q"])).Select(o => new { value = o.ID, text = o.DepName })));
            }
        }
        public void GetTaskCode()
        {
            string q = Request.Form["q"];
            if (q == null)
            {
                Response.Write(JsonHelper.toJson(DALSession.Current.TM_TaskAssignDAL.GetListBy(d => true).Select(o => new { value = o.TaskCode, text = o.TaskCode })));

            }
            else
            {
                Response.Write(JsonHelper.toJson(DALSession.Current.TM_TaskAssignDAL.GetListBy(d => d.TaskCode.Contains(q)).Select(o => new { value = o.TaskCode, text = o.TaskCode })));
            }
        }

        public void GetProjAndEng()
        {
            string taskCode = Request.Form["taskCode"];
            var taskAssign = DALSession.Current.TM_TaskAssignDAL.GetListBy(o => o.TaskCode == taskCode).FirstOrDefault();
            Response.Write(JsonHelper.toJson(new { projName = taskAssign.ProjName, engName = taskAssign.EngName }));
        }
        public void GetHmCode()
        {
            string q = Request.Form["q"];
                Response.Write(JsonHelper.toJson(DALSession.Current.BD_MaterialsDAL.GetListBy(o => o.State == "0" && o.HmCode.Contains(q)).Select(o => new { text = o.HmCode, value = o.HmCode })));
        }
        public void GetMaterial()
        {
            string hmCode = Request.Form["hmCode"];
            Response.Write(JsonHelper.toJson(DALSession.Current.BD_MaterialsDAL.GetListBy(o => o.HmCode == hmCode).FirstOrDefault()));

        }
        public void GetMaterialMsg()
        {
            string q = Request.Form["q"];
            var list = DALSession.Current.BD_MaterialsDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, o => o.HmCode.Contains(q), "Id", true).Select(o => new { Id = o.Id, HmCode = o.HmCode, Material = o.Material, Name = o.Name, Guige = o.Guige, Caizhi = o.Caizhi, PurcUnit = o.PurcUnit, Mweight = o.Mweight }).ToList();
            var count = DALSession.Current.BD_MaterialsDAL.GetCount(o => o.HmCode.Contains(q));
            Response.Write(JsonHelper.toPageJson(list,count));
        }
        public void GenerateNum()
        {
            var obj = DALSession.Current.StorageInDAL.GetListBy(o => true, o => o.Id, false).FirstOrDefault();
            string inCode = "";
            if (obj==null)
            {
                inCode = "RK00000001";
            }
            else
            {
                int num = Commons.String2Int32(obj.InCode.Substring(2));
                inCode = "RK" + (num + 1).ToString().PadLeft(8, '0');
            }
            Response.Write(inCode);
        }
        public void SaveStorageIn()
        {
            string action=Request.QueryString["action"];
            StorageManage.StorageIn storageIn = new StorageManage.StorageIn();
            List<StorageInDetail> info = JsonConvert.DeserializeObject<List<StorageInDetail>>(Request.Form["Info"]);
            ModelTools.Form2Model(Request.Form, storageIn);
            if (action=="add")
            { 
                int id = Commons.String2Int32(DALSession.Current.StorageInDAL.AddModelReturnId(storageIn));
                StorageInDetail storageInDetail = new StorageInDetail();
                info.ForEach(o =>
                {
                    o.MainId = id;
                    o.InGuid = Guid.NewGuid().ToString();
                    DALSession.Current.StorageInDetailDAL.Add(o);

                    Storage storage = new Storage();
                    storage.TaskCode = storageIn.TaskCode;
                    storage.ProjName = storageIn.ProjName;
                    storage.EngName = storageIn.EngName;
                    storage.InCode = storageIn.InCode;
                    storage.MaterialCode = o.MaterialCode;
                    storage.Guid = o.InGuid;
                    storage.ZhangNum = o.ZhangNum;
                    storage.TotalWeight = o.TotalWeight;
                    storage.Length = o.Length;
                    storage.Width = o.Width;
                    storage.MaterialType = o.MaterialType;
                    storage.Warehouse = storageIn.Warehouse;
                    storage.Note = storageIn.Note;
                    DALSession.Current.StorageDAL.Add(storage);
                });
                DALSession.Current.StorageDAL.SaveChanges();
            }
            else
            {
                //修改入库主表数据
                DALSession.Current.StorageInDAL.ModifyBy(storageIn, o => o.InCode == storageIn.InCode, "InTeam", "TaskCode", "ProjName", "EngName", "Warehouse", "Note"); 
                //修改入库明细表数据和新增数据
                info.ForEach(o=>{
                    var list=DALSession.Current.StorageInDetailDAL.GetListBy(s => s.Id == o.Id);
                    if (list==null || list.Count==0)
                    {
                        //新增
                        StorageInDetail storageInDetail = new StorageInDetail();
                        o.MainId = storageIn.Id;
                        o.InGuid = Guid.NewGuid().ToString();
                        DALSession.Current.StorageInDetailDAL.Add(o);

                        Storage storage = new Storage();
                        storage.TaskCode = storageIn.TaskCode;
                        storage.ProjName = storageIn.ProjName;
                        storage.EngName = storageIn.EngName;
                        storage.InCode = storageIn.InCode;
                        storage.MaterialCode = o.MaterialCode;
                        storage.Guid = o.InGuid;
                        storage.ZhangNum = o.ZhangNum;
                        storage.TotalWeight = o.TotalWeight;
                        storage.Length = o.Length;
                        storage.Width = o.Width;
                        storage.MaterialType = o.MaterialType;
                        storage.Warehouse = storageIn.Warehouse;
                        storage.Note = storageIn.Note;
                        DALSession.Current.StorageDAL.Add(storage);
                    }
                    else
                    {
                        //修改
                        DALSession.Current.StorageInDetailDAL.ModifyBy(o, s => s.Id == o.Id, "MaterialCode", "Length", "Width", "ZhangWeight", "ZhangNum", "TotalWeight", "MaterialType", "Note");
                        
                        Storage storage = new Storage();
                        storage.TaskCode = storageIn.TaskCode;
                        storage.ProjName = storageIn.ProjName;
                        storage.EngName = storageIn.EngName;
                        storage.MaterialCode = o.MaterialCode;
                        storage.ZhangNum = o.ZhangNum;
                        storage.TotalWeight = o.TotalWeight;
                        storage.Length = o.Length;
                        storage.Width = o.Width;
                        storage.MaterialType = o.MaterialType;
                        storage.Warehouse = storageIn.Warehouse;
                        storage.Note = storageIn.Note;
                        string guid = list.FirstOrDefault().InGuid;
                        DALSession.Current.StorageDAL.ModifyBy(storage, s => s.Guid == guid, "TaskCode", "ProjName", "EngName", "MaterialCode", "ZhangNum", "TotalWeight", "Length", "Width", "MaterialType", "Warehouse","Note");
                    }
                   
                });
                DALSession.Current.StorageInDAL.SaveChanges();

            }
            
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }
        public void GetViewStorageIn()
        {
            string inCode=Request.QueryString["inCode"];
            var list=DALSession.Current.View_StorageInDAL.GetListBy(o => o.InCode == inCode);
            var main = DALSession.Current.StorageInDAL.GetListBy(o => o.InCode == inCode).FirstOrDefault();
            Response.Write(JsonHelper.toJson(new { list = list, main = main }));
        }

        public void GetStorageList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"]!=null)
            {
                listSearch=ModelTools.GetSearchContions(Request.Form["searchData"]);
            }
            string OrderId = OperateContext.Sort == null ? "Id" : OperateContext.Sort;
            Expression<Func<View_Storage, bool>> exp = SearchExpression.FindByGroup<View_Storage>(listSearch);
            var list = DALSession.Current.View_StorageDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OperateContext.OrderDesc);
            int count = DALSession.Current.View_StorageDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));


        }
        public void GetStorageEdit()
        {
            string inCode=Request.QueryString["inCode"];
            var main=DALSession.Current.StorageInDAL.GetListBy(o => o.InCode == inCode).FirstOrDefault();
            var detail = DALSession.Current.View_StorageInDAL.GetListBy(o => o.InCode == inCode);
            Response.Write(JsonHelper.toJson(new { main=main,detail=detail}));
        }
        public void CheckCK()
        {
            string inCode = Request.QueryString["inCode"];
            var inList=DALSession.Current.View_StorageInDAL.GetListBy(o => o.InCode == inCode);
            int count = 0;
            inList.ForEach(o=>{
                count+= DALSession.Current.StorageOutDetailDAL.GetCount(s => s.OutGuid == o.InGuid);
            });
            
            if (count==0)
            {
                Response.Write(JsonHelper.toDefaultMsg(true));
            }
            else
            {
                Response.Write(JsonHelper.toDefaultMsg(false));
            }
        }
        public void DeteleStorageIn()
        {
            string inCode = Request.QueryString["inCode"];
            var inList = DALSession.Current.View_StorageInDAL.GetListBy(o => o.InCode == inCode);
            int count = 0;
            inList.ForEach(o =>
            {
                count += DALSession.Current.StorageOutDetailDAL.GetCount(s => s.OutGuid == o.InGuid);
            });

            if (count == 0)
            {
                int mainId=(int)inList.FirstOrDefault().MainId;
                inList.ForEach(o =>
                {
                    DALSession.Current.StorageDAL.DelBy(s => s.Guid == o.InGuid);
                });
                DALSession.Current.StorageInDetailDAL.DelBy(o => o.MainId == mainId);
                DALSession.Current.StorageInDAL.DelBy(o => o.InCode == inCode);
                DALSession.Current.StorageDAL.SaveChanges();
                Response.Write(JsonHelper.toDefaultMsg(true));
                
            }
            else
            {
                Response.Write(JsonHelper.toDefaultMsg(false));
            }
        }
    }
}